<?php

class _F_EXTENSION_ASSET_MANAGER_ extends _F_EXTENSION_ {
	
	public $mode = 'checksum';
	public $runtime_path = '/runtime/assets';
	public $prev_callback;
	
	public function __construct() {
		$this->prev_callback = f()->register_method(
			'asset_manager_callback',array($this,'_f_callback_'));
		f()->register_method('asset_manager',array($this,'asset_manager'));
	}
	
	public function asset_manager() {
		return $this;
	}
	
	public function _f_callback_($name,$file) {
		if (isset($this->prev_callback)) {
			$name = call_user_func($this->prev_callback,$name,$file);
			$file = f()->base_path.$name;
		}
		if ($this->mode === 'full') {
			$md5 = md5_file($file);
			$name = $this->runtime_path.'/a'.$md5.'.'.preg_replace('/^.*\./','',$file);
			if (!file_exists(f()->base_path.$name)) {
				$dir = f()->base_path.$this->runtime_path;
				if (!file_exists($dir)) mkdir($dir,0777,true);				
				copy($file,f()->base_path.$name);
			}
		} else if ($this->mode === 'checksum') {
			$md5 = md5_file($file);
			$name = $name.(strpos($file,'?') === false ? '?c' : '&c').$md5.'=';
		}
		return $name;
	}
	
}

new _F_EXTENSION_ASSET_MANAGER_;
